const fs = require("fs");
const path = require("path");
const formatNumber = require("./utils/formatNumber.js");
const getFormatDate = require("./utils/getFormatDate.js");

const templateDir = path.join(__dirname, "./sources/template");
const targetDir = path.join(__dirname, "../");

// 同步读取配置文件内容
const content = fs.readFileSync(path.join(__dirname, "config.json"), "utf8");

// 解析 json
let config = JSON.parse(content);

// 设置数字
config.count++;

// 获取日期
const [today, weekday] = getFormatDate();

// 创建目标目录
const targetDirPath = path.join(
  targetDir,
  `${formatNumber(config.count, 4)}_${today}`
);
try {
  fs.mkdirSync(targetDirPath, {
    recursive: true,
  });
} catch (error) {
  console.log("创建目录失败");
  console.log(error);
}

// 创建日报文件
const srcDailyPath = path.join(templateDir, "日报.md");
const targetDailyPath = path.join(targetDirPath, `日报${today}.md`);
try {
  // 读取模板文件内容
  const dailyContent = fs.readFileSync(srcDailyPath, "utf8");

  // 替换第一行
  const lines = dailyContent.split("\n");
  lines[0] = `${config.FilePrefix}${today}${config.DailyTitle}`;
  const newContent = lines.join("\n");

  // 写入目标文件
  fs.writeFileSync(targetDailyPath, newContent, "utf-8");
} catch (error) {
  console.log("创建日报文件失败");
  console.log(error);
}

// 创建周报文件
if (weekday) {
  // 说明需要产生周报
  const srcWeeklyPath = path.join(templateDir, "周报.md");
  const targetWeeklyPath = path.join(
    targetDirPath,
    `周报${weekday}至${today}.md`
  );

  try {
    // 读取模板文件内容
    let weeklyContent = fs.readFileSync(srcWeeklyPath, "utf8");

    // 替换第一行
    const lines = weeklyContent.split("\n");
    lines[0] = `${config.FilePrefix}${weekday}至${today}${config.WeeklyTitle}`;
    weeklyContent = lines.join("\n");

    // 写入目标文件

    fs.writeFileSync(targetWeeklyPath, weeklyContent, "utf-8");
  } catch (error) {
    console.log("创建周报文件失败");
    console.log(error);
  }
}

// 创建个人日志文件
const srcPersonDailyLogPath = path.join(templateDir, "个人日志.md");
const targetPersonDailyLogPath = path.join(
  targetDirPath,
  `个人日志${today}.md`
);
try {
  // 读取模板文件内容
  const personDailyLogContent = fs.readFileSync(srcPersonDailyLogPath, "utf8");

  // 替换第一行
  const lines = personDailyLogContent.split("\n");
  lines[0] = `${config.FilePrefix}${today}${config.PersonDailyLogTitle}`;
  const newContent = lines.join("\n");

  // 写入目标文件
  fs.writeFileSync(targetPersonDailyLogPath, newContent, "utf-8");
} catch (error) {
  console.log("创建个人日志文件失败");
  console.log(error);
}

// 同步写入配置文件
fs.writeFileSync(
  path.join(__dirname, "config.json"),
  JSON.stringify(config),
  "utf8"
);

console.log("日报，周报和个人日志创建成功");
